using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Numerics;
using Unity.VisualScripting;
using UnityEngine;
using UnityEngine.SceneManagement;
using UnityEngine.UIElements;
using Random = UnityEngine.Random;
using Vector2 = UnityEngine.Vector2;



public class GameManager : SingletonpatternMonoBase<GameManager>
{

    public List<Character> characters;

    public int currentIndex = 0;

    public int turnCount = 0;

    public bool isCanClick = true;

    public bool isNeedSave = true;

    public Character currentCharacter
    {
        get { return characters[currentIndex]; }
    }

    public int goldcoinNum = 0;

    public int growNum = 0;

 /*   public List<ActionClass> actions = new List<ActionClass>();

    void Start()
    {
        if (isNeedSave)
        {
            ShowPlayer();
            Save.SaveAll(0);
        }


        InitAllCharacter();

        ReMakeCharacter();


        UIManager.Instance.SetHPPosition(0);
        UIManager.Instance.UpdateBuffShow();
        UIManager.Instance.SetCurrentCharacterUI();
        ActionWheelController.Instance.GenerateButtons();
        ActionPointController.Instance.UpdateActionPoint();

    }
    public void InitAllCharacter()
    {
        characters = FindObjectsOfType<Character>().ToList();
        foreach (Character character in characters.ToList())
        {
            InitCharacter(character);

        }
    }
    public void InitCharacter(Character character)
    {
        character.CopyProperty();
        character.SetPos();
    }

    public void ReMakeCharacter()
    {


        characters = FindObjectsOfType<Character>().ToList();
        //处理
        foreach (Character character in characters.ToList())
        {
            if (character.isDead)
            {
                characters.Remove(character);
                Destroy(character.gameObject);

            }


        }


        SortCharacters();




    }


    private void SortCharacters()
    {
        characters.Sort((a, b) =>
        {
            if (a.currentProperty.initiative != b.currentProperty.initiative)
            {
                return b.currentProperty.initiative.CompareTo(a.currentProperty.initiative); // 降序排序
            }
            else
            {
                // initiative值相同，根据characterType排序
                int aType = GetTypePriority(a.characterType);
                int bType = GetTypePriority(b.characterType);
                return aType.CompareTo(bType);
            }
        });

        // 获取characterType的优先级
        int GetTypePriority(CharacterType characterType)
        {
            switch (characterType)
            {
                case CharacterType.player:
                    return 1; // Friend优先级最高
                case CharacterType.enemy:
                    return 2; // Enemy优先级中等
                default:
                    return 3; // other优先级最低
            }
        }
    }

    void RecoveryActionPoint()
    {
        foreach (Character character in characters)
        {
            character.currentProperty.actionPoint = character.originalProperty.actionPoint;


            character.healthUI.SetActionPoint();
            ActionPointController.Instance.UpdateActionPoint();




        }
    }
    public void MoveToNextCharacter()
    {




        if (isCanClick == false) return;







        CheckBuffEnd();
        currentIndex++;

        if (currentIndex > characters.Count - 1)
        {
            turnCount++;

            currentIndex = 0;

            ReMakeCharacter();

            RecoveryActionPoint();

            UIManager.Instance.UpdateTurnCount();



        }


        UIManager.Instance.SetCurrentCharacterUI();



        CheckBuffBegin();



        StartCoroutine(ExecuteActions());



        UIManager.Instance.DestroyAllYellow();




        ActionWheelController.Instance.GenerateButtons();



    }
    IEnumerator ExecuteActions()
    {
        yield return StartCoroutine(CheckDelayAction());

        if (currentIndex < characters.Count && currentCharacter.isDead)
        {
            // 为了避免无限递归，添加一个安全检查
            // 确保不是所有角色都已经检查过且死亡
            bool allDead = characters.All(c => c.isDead);
            if (!allDead)
            {
                MoveToNextCharacter();
                yield break;

            }
            else
            {
                // 所有角色都死亡的处理逻辑（如果有的话）
                Debug.Log("All characters are dead.");
            }
        }

        if (currentCharacter.characterType == CharacterType.enemy)
        {
            yield return StartCoroutine(currentCharacter.PerformAIAction());
        }
    }
    IEnumerator CheckDelayAction()
    {
        Character character = currentCharacter;

        if (character.isDead || !character.gameObject.activeSelf)
        {
            yield break; // 如果角色已经被销毁或不活跃，跳过当前迭代
        }
        foreach (DelayAction delayActionClass in character.GetComponents<DelayAction>())
        {
            yield return new WaitUntil(() => isCanClick == true);
            if (delayActionClass.isClick)
            {
                delayActionClass.nowTime++;
                delayActionClass.ActionBegin();
            }
        }
        foreach (DelayWaitAction delayWaitActionClass in character.GetComponents<DelayWaitAction>())
        {
            yield return new WaitUntil(() => isCanClick == true);
            if (delayWaitActionClass.isClick)
            {
                delayWaitActionClass.nowTime++;
                delayWaitActionClass.ActionBegin();
            }
        }
        yield return new WaitUntil(() => isCanClick == true);

    }
    public void ShowAttackWarn()
    {
        foreach (Character character in characters)
        {
            foreach (DelayAction delayActionClass in character.GetComponents<DelayAction>())
            {

                if (delayActionClass.isClick && delayActionClass.nowTime + 1 == delayActionClass.delayTime)
                {
                    delayActionClass.ShowRedGrid();
                }
            }
            foreach (DelayWaitAction delayWaitActionClass in character.GetComponents<DelayWaitAction>())
            {

                if (delayWaitActionClass.isClick && delayWaitActionClass.nowTime + 1 == delayWaitActionClass.delayTime)
                {
                    delayWaitActionClass.ShowRedGrid();
                }
            }
        }
    }
    void CheckBuffEnd()
    {
        Character character = currentCharacter;
        if (character.isDead || !character.gameObject.activeSelf)
        {
            return; // 如果角色已经被销毁或不活跃，跳过当前迭代
        }
        // 使用ToList()创建buffs的副本进行迭代
        foreach (BuffClass buff in character.buffs.ToList())
        {
            buff.TickEnd(character);
            UIManager.Instance.UpdateBuffShow();
        }

    }
    void CheckBuffBegin()
    {
        Character character = currentCharacter;

        if (character.isDead || !character.gameObject.activeSelf)
        {
            return; // 如果角色已经被销毁或不活跃，跳过当前迭代
        }
        // 使用ToList()创建buffs的副本进行迭代
        foreach (BuffClass buff in character.buffs.ToList())
        {
            buff.TickBegin(character);
            UIManager.Instance.UpdateBuffShow();
        }

    }


    public void RecordAction(ActionClass actionClass)
    {
        actions.Add(actionClass);
    }

    public void GoldcoinChange(int num)
    {
        goldcoinNum += num;
        UIManager.Instance.UpdateGoldcoinNum();
    }

    public void GrowlNumChange(int num)
    {
        growNum += num;
        UIManager.Instance.UpdateGrowNum();

    }


















    public GameObject[] playerPres;
    void ShowPlayer()
    {
        Save save = Save.LoadAll();

        GoldcoinChange(save.goldcoinNum);

        GrowlNumChange(SaveGrowth.LoadInfo().growNum);

        for (int i = 0; i < save.playerID.Count; i++)
        {

            Vector2 vector2 = new Vector2(Random.Range(0, GridManager.Instance.maxRow), Random.Range(0, GridManager.Instance.maxCol));

            int a = int.Parse(SceneManager.GetActiveScene().name);
            if (a <= 3)
            {
                a = 3;
            }
            else if (a <= 6)
            {
                a = 4;
            }
            else
            { a = 5; }

            GenerateCharacter(save.playerID[i], save.actions[i], save.property[i], new Vector2(i / a, i % a));


        }
    }
    public GameObject GenerateCharacter(int id, IntList actionId, Property property, Vector2 postion)
    {


        GameObject a = Instantiate(playerPres[id]);



        a.GetComponent<Character>().playerState = PlayerState.Battle;

        a.GetComponent<Character>().characterID = id;

        a.GetComponent<Character>().originalProperty = property;

        //
        for (int j = 0; j < actionId.list.Count; j++)
        {
            a.AddComponent(SaveClass.actionIDToType[actionId.list[j]].actionType);
        }





        a.GetComponent<Character>().characterGrid = GridManager.Instance.gridsXY[(int)postion.x, (int)postion.y];



        a.GetComponent<Character>().spriteIcon = Resources.Load<Sprite>("PlayerIcon/" + id);


        InitCharacter(a.GetComponent<Character>());

        return a;
    }*/
}


